﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using AllInOnePluginBL.Helpers;
using NLog;

namespace AllInOnePluginBL.FileHostingExtractors
{
    /// <summary>
    /// Summary description for MultiUploadExtractor
    /// </summary>
    public class MultiUploadExtractor : IFileHostingExtractor
    {
        private readonly Logger _log = LogManager.GetLogger("MultiUploadExtractor");
        private const string MULTIUPLOAD_URL_REGEX = @"multiupload\.com.*?[=,/](.{10})";
        private const string MULTIUPLOAD_URL = @"http://www.multiupload.com/{0}";

        public List<string> GetMovieUrls(string content)
        {
            var movieUrls = new List<string>();

            var matches = Regex.Matches(content, MULTIUPLOAD_URL_REGEX, RegexOptions.Singleline);
            foreach (Match linkMatch in matches)
            {
                if (linkMatch.Groups[1].Value.Contains("/")) continue;
                var fullLink = string.Format(MULTIUPLOAD_URL, linkMatch.Groups[1].Value);
                if (movieUrls.Contains(fullLink)) continue;

                var pageContent = Utils.GetPage(fullLink, Encoding.UTF8);
                if (pageContent.Contains(".rar") || pageContent.Contains(".zip") ||
                    pageContent.Contains("Unfortunately, the link you have clicked is not available"))
                    continue;
                movieUrls.Add(fullLink);

                ExtractOtherLinks(pageContent, ref movieUrls);
            }

            return movieUrls;
        }

        private void ExtractOtherLinks(string pageContent, ref List<string> movieUrls)
        {
            if (pageContent.Contains("http://www.multiupload.com/MU_"))
            {
                var video_link = Regex.Match(pageContent, "alt=\"Megaupload\".*?<a href=\"(.+?)\"", RegexOptions.Singleline).Groups[1].Value;

                var redirectUrl = GetRedirectAddress(video_link);

                if (!string.IsNullOrEmpty(redirectUrl) && !movieUrls.Contains(redirectUrl))
                {
                    movieUrls.Add(redirectUrl);
                }
            }
        }

        private string GetRedirectAddress(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("UserAgent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");

            WebResponse response = null;
            try
            {
                response = request.GetResponse();
                return request.Address.ToString();
            }
            catch(Exception)
            {
                return string.Empty;
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
        }

        public VideoResult ExtractMovieUrl(string movieUrl)
        {
            var pageContent = Utils.GetPage(movieUrl, Encoding.UTF8);
            if (pageContent.Contains(".rar"))
            {
                return new VideoResult(movieUrl, false);
            }

            var multiUploadVideoLink = Regex.Match(pageContent,
                                                   "<div id=\"downloadbutton_\".*?<script.*?.href='(.+?)';.*?</script>",
                                                   RegexOptions.Singleline).Groups[1].Value;
            if(string.IsNullOrEmpty(multiUploadVideoLink))
            {
                return new VideoResult(movieUrl, false);
            }

            var startIndex = multiUploadVideoLink.LastIndexOf("/");
            var movieName = multiUploadVideoLink.Substring(startIndex +1);

            _log.Debug("MultiUploadExtractor::ExtractMovieUrl: {0}", multiUploadVideoLink);

            return new VideoResult(multiUploadVideoLink, movieName, true);
        }

        public bool IsContainVideoLink(string content)
        {
            return content.Contains("multiupload");
        }
    }
}